﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DNT.RavenQA.Core.Extensions;
using StructureMap;

namespace DNT.RavenQA.Web.Infrastructure.IoC
{
    public class StructureMapDependencyResolver : IDependencyResolver
    {
        public StructureMapDependencyResolver(IContainer container)
        {
            container.EnsureIsNotNull("container");
            _container = container;
        }

        private readonly IContainer _container;

        public Object GetService(Type serviceType)
        {
            if (serviceType.IsNull())
                return null;

            Object result = null;

            try
            {
                result = serviceType.IsAbstract || serviceType.IsInterface
                         ? _container.TryGetInstance(serviceType)
                         : _container.GetInstance(serviceType);
            }
            catch (StructureMapException) { }

            return result;
        }

        public IEnumerable<Object> GetServices(Type serviceType)
        {
            try { return _container.GetAllInstances(serviceType).Cast<Object>(); }
            catch (StructureMapException) { return null; }
        }
    }
}